<?php
abstract class CF_App_Controller_Response_Abstract extends CF_Component
{
	/**
	 * 
	 * @var CF_App_Controller_Response_Header
	 */
	protected $_header;
	
	/**
	 * 
	 * @var mixed
	 */
	protected $_body;
	
	/**
	 * @return void
	 */
	public function __construct()
	{
		$this->addEvents(
			'beforesend',
			'send',
			'beforesendbody'
		);
	}
	
	/**
	 * @return string
	 */
	abstract public function getBodyContent();
	
	/**
	 * @return CF_App_Controller_Response_Header
	 */
	public function getHeader()
	{
		if(null == $this->_header){
			$this->_header = new CF_App_Controller_Response_Header();
		}
		return $this->_header;
	}
	
	/**
	 * 
	 * @param CF_App_Controller_Response_Header $header
	 * @return CF_App_Controller_Response $this
	 */
	public function setHeader(CF_App_Controller_Response_Header $header)
	{
		$this->_header = $header;
		return $this;
	}
	
	/**
	 * @return mixed
	 */
	public function getBody()
	{
		return $this->_body;
	}
	
	public function setBody($body)
	{
		$this->_body = $body;
		return $this;	
	}
	
	public function send($body = null)
	{
		if(null !== $body) $this->setBody($body);
		
		# notify before send event
		if(CF_Observable::VALUE_RETURN === $this->fireEvent('beforesend', array($this))) return;
		
		$this->getHeader()->send();
		
		$content = $this->getBodyContent();
		# notify before send body event
		if(CF_Observable::VALUE_RETURN === $this->fireEvent('beforesendbody', array($this, &$content))) return;
		
		echo $content;
		//echo '{"type":"rpc","tid":2,"action":"page","method":"load","result":{"total":1000,"rows":[{"id":1,"name":"abc"},{"id":2,"name":"def"}]}}';
		
		# notify send event
		$this->fireEvent('send', array($this, &$content));
		exit;
	}
	
	/**
	 * @return string
	 */
	public function __toString()
	{
		ob_start();
		$this->send();
		return ob_get_clean();
	}
}